package com.songtech.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import com.songtech.auth.resource.model.Resources;
import com.songtech.auth.role.model.Role;
import com.songtech.auth.role.service.RoleService;
import com.songtech.auth.user.model.User;
import com.songtech.auth.user.service.UserService;

public class AuthRealm extends AuthorizingRealm{

	private Logger logger = Logger.getLogger(AuthRealm.class);
	
	@Autowired
    @Lazy
	private UserService userService;
	
	@Lazy
	@Autowired
	private RoleService roleService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String loginName = (String)principals.fromRealm(getName()).iterator().next();
		User user = userService.queryUserByName(loginName);
		if(user != null){
			SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
			List<Role> roleList = userService.getUserRoles(loginName);
			List<String> roles = new ArrayList<String>();
			if(CollectionUtils.isNotEmpty(roleList)){
				for (Role role : roleList) {
					roles.add(role.getName());
					List<Resources> rescList = roleService.getRoleRes(role.getId());
					List<String> rescs = new ArrayList<String>();
					if(CollectionUtils.isNotEmpty(rescList)){
						for (Resources res:rescList){
							rescs.add(res.getUrl());
						}
						authorizationInfo.addStringPermissions(rescs);
					}
				}
				authorizationInfo.addRoles(roles);
			}
			return authorizationInfo;
		}
		return null;
	}

	/**
	 * 
	 * 登录认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) 
			throws AuthenticationException {
    	String loginName = (String)authToken.getPrincipal();
    	User user = userService.queryUserByName(loginName);
    	if(user == null){
    		 logger.info("未找到用户信息");
    		 throw new AuthenticationException("username \""+loginName+"\" is not found user");
    	}
    	SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user.getUserName(),user.getPassword(),getName());
		return authenticationInfo;
	}
}